<?php

class Application_Model_DbTable_Photos extends Zend_Db_Table_Abstract
{
    protected $_name = 'photos';

    /*
     *
     * @$type - string 'shtory' OR 'toys'
     *
     * return array()
     */
    public function getById($id, $type)
    {
        $select =  $this->select()
                        ->where('category = ?', $type)
                        ->order('id_ph');

        $data = $this->fetchAll($select)
                     ->toArray();

        $countData = count($data);

        $result = array();

        if (isset($data[$id - 1])) {
            $result['img'] = '/images/' . $type . '/' . $data[$id - 1]['link_ph'];
            $result['count'] = $countData;
            $result['next'] = ($id != $countData) ? $id + 1 : 1;
            $result['prev'] = ($id != 1) ? $id - 1 : $countData;
        } else {
            $result['error'] = 'error';
        }

        return $result;
    }

    /**
     *
     * @param string $type
     * @return array
     */
    public function getByType($type)
    {
        $select =  $this->select()
                        ->where('category = ?', $type)
                        ->order('id_ph');

        $data = $this->fetchAll($select)
                     ->toArray();

        $result = array();
        foreach ($data as $item) {
            $result[] = array(
                'thumb' => '/thumbs/' . $type . '/60/' . $item['link_ph'],
                'image' => '/images/' . $type . '/' . $item['link_ph'],
            );
        }

        return $result;
    }

    public function saveSrcImage($filename, $type)
    {
        $data = array(
                    'link_ph'  => $filename,
                    'category' => $type,
                );

        return $this->insert($data);
    }

    public function getAllImage()
    {
        $select =  $this->select()
                        ->order('id_ph DESC');

        $data = $this->fetchAll($select)
                     ->toArray();

        return $data;
    }

    public function deleteImage($id)
    {
        $select =  $this->select()
                        ->where('id_ph = ?', $id);
        $img = $this->fetchRow($select);

        $file = realpath(dirname('.') . '/images/' . $img->category . '/' . $img->link_ph);

        if (is_file($file)) {
            unlink($file);
        }

        $this->delete('id_ph = ' . $id);
    }
}
